//
//  QwardView.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/2/23.
//  Copyright © 2016年 game. All rights reserved.
//

#import "QwardView.h"
#import "QwarSelectView.h"
#import "SelectAwardModel.h"
#import "SelectAwardListModel.h"
#import "EvaluateModel.h"
CG_INLINE void AlertLog (NSString *titleStr,NSString *message,NSString *button1,NSString *button2)
{
    if(!titleStr)
        titleStr = @"";
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: titleStr
                                                        message: message
                                                       delegate: nil
                                              cancelButtonTitle: button1
                                              otherButtonTitles: button2,
                              nil];
    [alertView show];
    
}

#define backDefulHight (SCREEN_HEIGHT*0.7)

@interface QwardView ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate,UITextFieldDelegate,UIGestureRecognizerDelegate>
/**
 *  顶部灰色 View
 */
@property (nonatomic,strong) UIView *headerView;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,assign) CGFloat SelectHight;
@property (nonatomic,strong) UITextView *textView;
@property (nonatomic,strong) UILabel *placeHolderLabel;//textView中的水印字体label
@property (nonatomic,strong) UIButton *informBtn;
@property (nonatomic,strong) UIButton *sureBtn;
@property (nonatomic,assign) BOOL isText;


@property (nonatomic,assign) CGFloat backViewYY;

@property (nonatomic,copy) NSString *ssss;
@end

@implementation QwardView

-(NSString *)ssss{
    if (!_ssss) {
        _ssss = @"";
    }
return _ssss;
}

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = TouMingBlack;
        UITapGestureRecognizer *selsTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selfTap)];
        selsTap.delegate = self;
        [self addGestureRecognizer:selsTap];
        
        self.bacView.backgroundColor = [UIColor whiteColor];
        
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];//在这里注册通知  观察键盘变化
   
    }
    return self;
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];  // 动画的持续时间
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];// 键盘的frame
    
    [UIView animateWithDuration:duration animations:^{
        // 工具条的Y值 == 键盘的Y值 - 工具条的高度
        if (keyboardF.origin.y == SCREEN_HEIGHT) { // 键盘的Y值已经远远超过了view的高度 此时View的Y值为负值
            
               self.bacView.y = self.backViewYY;
            
            } else { //键盘弹出时  视图上升
     
            if (self.isText) {
                self.bacView.y =   keyboardF.origin.y - self.bacView.height;
            }
        }
    }];
}

/**
 *  白色View
 */
-(UIView *)bacView{
    if (!_bacView) {
        
        CGFloat yy;
        if (kDIEIsIPhone4SOrLess) {
            yy = (SCREEN_HEIGHT*0.2-50)-15;
        }else{
            yy = (SCREEN_HEIGHT*0.2-50);
        }
        
        _bacView = [[UIView alloc]initWithFrame:CGRectMake(15, yy, SCREEN_WIDTH-30, backDefulHight)];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapTap)];
        tap.delegate = self;
        [_bacView addGestureRecognizer:tap];
        
        [self addSubview:_bacView];
        
        [self CreatSelectView];
    
    }
        return _bacView;
}
/**
 * 点击白色View  收起键盘
 */
-(void)tapTap{
        
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
/**
 *  点击整个视图
 */
-(void)selfTap{
    self.alpha = 0;
   [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [self.selctCtrl.view sendSubviewToBack:self];
}
-(void)creatView
{
    _headerView=[[[NSBundle mainBundle] loadNibNamed:@"QwarHead" owner:nil options:nil] lastObject];
    _headerView.frame=CGRectMake(0, 0, W(_bacView), SCREEN_HEIGHT*0.05);
    [self.bacView addSubview:_headerView];
}

-(void)setIsclick:(BOOL)isclick{
    
    if (self.Isrefresh==NO) {
        [self CreatSelectView];
    }

}
-(void)CreatSelectView{
    
    
    [self.bacView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
          [self creatView];
    [[Manager sharedManager]RequestWhithURL:QwardConutUrl AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        
        if (error) {
            
            self.fileString = @"网络异常";
        }else{
            if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
                
                self.awardModel = [[SelectAwardModel alloc]initWithDictionary:responseObject[@"data"] error:nil];
                
                CGFloat hh = H(_bacView)*0.12;
                
                if (self.awardModel.score_list.count==0) {
                    self.fileString = @"抱歉，您分值不够，不能进行打赏";
                }else{
                
                    self.fileString = @"YES";
                    for (int i = 0; i<self.awardModel.score_list.count; i++) {
                        
                        QwarSelectView *select = [[QwarSelectView alloc]initWithFrame:CGRectMake(0, Height(_headerView)+(hh+1)*i, W(_bacView), hh)];
                        select.result.delegate = self;
                        select.model = self.awardModel.score_list[i];
                        [self.bacView addSubview:select];
                        
                        select.selectBtn.tag = i+100;
                        [select.selectBtn addTarget:self action:@selector(SelectClick:) forControlEvents:UIControlEventTouchUpInside];
                        select.result.tag = i+100000;
                        
                        CGFloat yyy = Height(select)-H(select)*1/6;
                        
                        [self CreattableViewWhithPointY:yyy AndTag:i+1000];
                        
                        self.SelectHight = Height(select);
                    }
                    
                    [self CreatTextView];
                    [self CreatSureClick];
                    
                    self.Isrefresh = YES;

                }
                
                
            
            }else{
            
                self.fileString = responseObject[@"message"];
            }
        
        }
    }];
    
}

-(void)SelectClick:(UIButton *)btn{
    
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
    /**
     *  总共有四个 btn 四个tableview 每次点击时就遍历 tag值  把另外3个都关掉
     */
    for (int i=0; i<4; i++) {
        
        if (i == btn.tag-100) {
            
        }else{
            UITableView *tableview = [self.bacView viewWithTag:i+1000];
            tableview.height = 0;
            
                    UIButton *bnt = [self.bacView viewWithTag:i+100];
                    bnt.selected = NO;
        }
   
    }
    
     btn.selected = !btn.selected;
    UITableView *tableview = [self.bacView viewWithTag:btn.tag-100+1000];
    [self.bacView bringSubviewToFront:tableview];

    [UIView animateWithDuration:0.3 animations:^{
        if (btn.selected) {
            tableview.height = 120;
            [self.bacView bringSubviewToFront:tableview];
        }else{
            tableview.height = 0;
        }
    }];
}

-(void)CreatTextView{
    [_textView removeFromSuperview];
    _textView = [[UITextView alloc]initWithFrame:CGRectMake(10, self.SelectHight+8, W(_bacView)-20, backDefulHight*0.15)];
    _textView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _textView.layer.borderWidth = 0.5;
    _textView.returnKeyType = UIReturnKeyDone;
    _textView.delegate = self;
    radius(_textView, 2);
    _textView.font = font(SCREEN_WIDTH*0.042);
    [self.bacView addSubview:_textView];
    
    //水印字体
    [_placeHolderLabel removeFromSuperview];
    _placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, CGRectGetWidth(_textView.frame), 30)];
    _placeHolderLabel.textColor = [UIColor lightGrayColor];
    _placeHolderLabel.font = font(SCREEN_WIDTH*0.04);
    _placeHolderLabel.userInteractionEnabled = NO;
    _placeHolderLabel.text = @"请输入你打赏的理由";
    _placeHolderLabel.hidden = ![@"" isEqualToString:self.textView.text];
    [_textView addSubview:_placeHolderLabel];
}

/**
 *  textView下方部分 通知作者、确定
 */
-(void)CreatSureClick{
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(15, Height(_textView)+5, 200, backDefulHight*0.04)];

    lab.textColor = RGBAS;
    lab.text = @"打赏扣除自身相应积分";
    lab.font = font(SCREEN_WIDTH*0.041);
    [self.bacView  addSubview:lab];
    
    _informBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _informBtn.frame = CGRectMake(15, Height(lab)+10, backDefulHight*0.04, backDefulHight*0.04);
    _informBtn.adjustsImageWhenHighlighted = NO;
    [_informBtn setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateSelected];
    [_informBtn setImage:[UIImage imageNamed:@"empty"] forState:UIControlStateNormal];
    _informBtn.selected = YES;
    [_informBtn addTarget:self action:@selector(informClick:) forControlEvents:UIControlEventTouchUpInside];
    [_bacView addSubview:_informBtn];
    
    UILabel *info = [[UILabel alloc]initWithFrame:CGRectMake(Width(_informBtn)+5, Y(_informBtn), 100, H(_informBtn))];
    info.text = @"通知作者";
    info.textColor = textcolor;
    info.font = font(SCREEN_WIDTH*0.045);
    [_bacView addSubview:info];
    
    _sureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _sureBtn.frame = CGRectMake(X(_informBtn), Height(_informBtn)+10, W(_bacView)-2*X(_informBtn),  backDefulHight*0.1);
    
    [_sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [_sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _sureBtn.backgroundColor = mainColor;
    [_bacView addSubview:_sureBtn];
    [_sureBtn addTarget:self action:@selector(sureClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.bacView.height = Height(_sureBtn)+15;
    self.bacView.y = (SCREEN_HEIGHT-self.bacView.height)/2;
    self.backViewYY = self.bacView.y;
    _headerView.frame=CGRectMake(0, 0, W(_bacView), SCREEN_HEIGHT*0.05);
}

#pragma mark---点击确定
-(void)sureClick{
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    [dic addEntriesFromDictionary: @{@"tid":self.tid,
                                     @"pid":self.pid,
                                     @"formhash":self.formhash,
                                     }];

    if (self.textView.text.length!=0) {
        [dic addEntriesFromDictionary: @{@"reason":self.textView.text}];
    }else{
    
         [dic addEntriesFromDictionary: @{@"reason":@" "}];
    }
    
   
    NSMutableArray *scoreAr = [NSMutableArray array];
    
    for (int i=0; i<self.awardModel.score_list.count; i++) {
        
        UITextField *text = [self viewWithTag:i+100000];

        if (text.text.length!=0) {
            SelectAwardListModel *model = self.awardModel.score_list[i];
            NSString *name;
            if ([model.extcredit isEqualToString:@"威望"]) {
                name = @"score1";
            }else if ([model.extcredit isEqualToString:@"金钱"]){
                name = @"score2";
            }else if ([model.extcredit isEqualToString:@"贡献"]){
                 name = @"score3";
            }else if ([model.extcredit isEqualToString:@"钓币"]){
                 name = @"score4";
            }
            
            EvaluateModel *evalua = [[EvaluateModel alloc]initWithDictionary:@{@"extcredits":model.extcredit,@"totoal_rate":text.text} error:nil];
            [scoreAr addObject:evalua];
   
            [dic addEntriesFromDictionary: @{name:text.text}];

        }
    }


  [[Manager sharedManager]RequestWhithURL:GetFormhash AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
            
            [dic addEntriesFromDictionary:@{@"formhash":responseObject[@"data"][@"formhash"]}];
            
            [self GetAwardWhithDic:[dic mutableCopy] AndScorAr:[scoreAr mutableCopy]];
        
        }else{
            [Manager GetHudWhithText:@"打赏失败" AndFatherView:self];
        
        }
    }];

}

-(void)GetAwardWhithDic:(NSDictionary *)dic AndScorAr:(NSArray *)scoreAr{


    [[Manager sharedManager]ResponseWhithURL:SelectAwardUrl AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
        
        if ([responseObject[@"status"]isEqualToString:@"SUCCESS"]) {
            
            [self.deleget AwardSuccess:[scoreAr copy]];
            self.Isrefresh = NO;
            self.alpha = 0;
            [self.selctCtrl.view sendSubviewToBack:self];

            AlertLog(@"打赏成功", nil, @"确定", nil);
        }else{
            
            [Manager GetHudWhithText:responseObject[@"message"] AndFatherView:self];
        }
        
    }];
}

-(void)informClick:(UIButton *)btn{
    btn.selected = !btn.selected;
}

-(void)CreattableViewWhithPointY:(CGFloat )yy AndTag:(NSInteger)tag{
    CGFloat www= W(_bacView)/3;

   UITableView *tablview = [[UITableView alloc]initWithFrame:CGRectMake((W(_bacView)-www)/2,yy, www, 0) style:UITableViewStylePlain];
    [tablview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    tablview.delegate = self;
    tablview.tag = tag;
    tablview.dataSource = self;
    tablview.bounces = NO;
    tablview.backgroundColor = [UIColor whiteColor];
    tablview.layer.borderWidth = 0.5;
    tablview.layer.borderColor = [UIColor lightGrayColor].CGColor;
    
    [self.bacView addSubview:tablview];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

        SelectAwardListModel *list = self.awardModel.score_list[tableView.tag-1000];
            return (list.max.integerValue-list.min.integerValue)+1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return ((H(_bacView)*0.14))*2/3;
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.contentView.backgroundColor = [UIColor whiteColor];
    
    SelectAwardListModel *list = self.awardModel.score_list[tableView.tag-1000];

    cell.textLabel.text = [NSString stringWithFormat:@"%ld",(list.min.integerValue+indexPath.row)];
    cell.textLabel.font = Countfont(SCREEN_WIDTH*0.042);
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UITextField *text = [self.bacView viewWithTag:(tableView.tag-1000)+100000];
    
    text.text = cell.textLabel.text;
    
    [self CloseAll];
}

#pragma mark - text view delegate
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    
    if ([text isEqualToString:@"\n"]) {
        [_textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView{
    _placeHolderLabel.hidden = ![@"" isEqualToString:textView.text];
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    [self CloseAll];
        self.isText = YES;
    
    return YES;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [self CloseAll];
    self.isText = NO;
    
    self.ssss = textField.text;
    return YES;
}


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    SelectAwardListModel *list = self.awardModel.score_list[textField.tag-100000];
    self.ssss = [self.ssss stringByAppendingString:string];

    if (self.ssss.integerValue<list.min.integerValue) {
        self.ssss = @"";
        return NO;
    }
    
    
    if (self.ssss.integerValue>list.max.integerValue){
    
        self.ssss = [self.ssss substringToIndex:self.ssss.length-1];
        return NO;
    }
    
    if (range.length==1) {
        self.ssss = [self.ssss substringToIndex:self.ssss.length-1];
    }
    
    return YES;
}



/**
 *  将tabview全部关闭  btn的select全部设为NO
 */
-(void)CloseAll{
    for (int i=0; i<4; i++) {
        
        UITableView *tableview = [self.bacView viewWithTag:i+1000];
        tableview.height = 0;
        
        UIButton *bnt = [self.bacView viewWithTag:i+100];
        bnt.selected = NO;
    }
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 *  对某些手势进行 禁用
 */
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        
        return NO;
    }
    
    return YES;
}

@end
